<template>
    <div class="jianzhan-content">
        <crumb :name="$t('servicePurchase.purchaseOrder')"></crumb>
        <div class="content">
            <el-button
                    type="primary"
                    icon="el-icon-plus"
                    style="float: left;margin: 10px 0"
                    @click="openAdd"
            >{{$t('add')}}
            </el-button>
            <div class="table-wrapper">
                <el-table
                        :data="list"
                        @expand-change="expand"
                        stripe
                        border
                        row-key="id"
                        style="width: 100%">
                    <el-table-column
                            type="expand"
                    >
                        <template slot-scope="scope">
                            <el-table
                                    :data="scope.row.partList"
                                    stripe
                                    border
                                    style="width: 100%">
                                <el-table-column
                                        prop="partsNumber"
                                        :label="$t('part.partNo')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="denomination"
                                        :label="$t('part.description')"
                                >
                                    <template slot-scope="scope">
                                        {{scope.row.denomination}} {{scope.row.designation}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="systemName"
                                        :label="$t('part.system')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="hostNumber"
                                        :label="$t('part.unit')"
                                >
                                </el-table-column>

                                <el-table-column :label="$t('part.qty')"
                                                 prop="partsQuantity"
                                >

                                </el-table-column>

                                <el-table-column
                                        prop="purchasePriceChn"
                                        :label=" $t('part.priceC')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="purchasePriceIdr"
                                        :label="$t('part.priceI')"
                                >
                                </el-table-column>

                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column
                            header-align="center"
                            align="center"
                            prop="purchaseNumber"
                            :label="$t('servicePurchase.purchaseNo')"
                    >
                    </el-table-column>
                    <el-table-column
                            header-align="center"
                            align="center"
                            prop="purchaseMethod"
                            :label="$t('servicePurchase.purchaseMethod')"
                    >
                        <template slot-scope="scope">
                            {{methods[scope.row.purchaseMethod]}}
                        </template>
                    </el-table-column>
                    <el-table-column
                            header-align="center"
                            align="center"
                            prop="purchaseDateStr"
                            :label="$t('servicePurchase.date')"
                    >
                    </el-table-column>
                    <el-table-column
                            :label="$t('operate')"
                    >
                        <template slot-scope="scope">
                            <el-button type="text"
                                       size="small"
                                       @click="edit(scope.row)"
                                       icon="el-icon-edit">{{$t('edit')}}
                            </el-button>
                            <el-button type="danger" @click="deleteOrder(scope.row)">{{$t('delete')}}</el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
            <div class="page">
                <pagination :pageSize="pageSize" :total="total"></pagination>
            </div>
        </div>
        <el-dialog
                :title="$t('servicePurchase.purchase')"
                :visible.sync="dialogVisible"
                width="90%"
        >
            <el-form ref="form"
                     :rules="rule"
                     style="text-align: left"
                     :model="po"
                     label-width="180px" inline>
                <el-form-item :label="$t('servicePurchase.purchaseNo')"
                              prop="purchaseNumber">
                    <el-input v-model="po.purchaseNumber"
                              :placeholder="$t('servicePurchase.purchaseNo')"
                              size="small"></el-input>
                </el-form-item>
                <el-form-item :label="$t('servicePurchase.purchaseMethod')" prop="purchaseMethod">
                    <el-select v-model="po.purchaseMethod" :placeholder="$t('servicePurchase.purchaseMethod')"
                               size="small">
                        <el-option
                                v-for="item in [
                                    {id:1,name:$t('consignment')},
                                    {id:2,name:$t('import')},
                                    {id:3,name:$t('local')},
                                    {id:4,name:$t('factory')}
                                ]"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item :label="$t('servicePurchase.date')">
                    <el-date-picker v-model="po.purchaseDateStr"
                                    type="date"
                                    size="small"
                                    value-format="yyyy-MM-dd"
                                    :placeholder="$t('servicePurchase.date')"></el-date-picker>
                </el-form-item>

                <el-form-item :label="$t('servicePurchase.department')"
                >
                    <el-input v-model="po.applyDepartment"
                              :placeholder="$t('servicePurchase.department')"
                              size="small"></el-input>
                </el-form-item>
                <el-form-item :label="$t('servicePurchase.applier')"
                >
                    <el-input v-model="po.applicant"
                              :placeholder="$t('servicePurchase.applier')"
                              size="small"></el-input>
                </el-form-item>

                <div>
                    <el-form-item :label="$t('upload')"
                    >
                        <label for="purchaseFile" class="label">
                            {{$t('upload')}}
                            <i class="el-icon-upload"></i>
                        </label>
                        <input type="file" v-show="false" id="purchaseFile" @change="fileChange"/>
                        <a class="label" @click="downloadTemplate">{{$t('downloadTemplate')}}</a>
                    </el-form-item>
                </div>
                <el-button type="text" icon="el-icon-plus" @click="dbVisible = true">{{$t('add')}}</el-button>
                <el-table
                        :data="partList"
                        stripe
                        border
                        style="width: 100%">
                    <el-table-column
                            prop="partsNumber"
                            :label="$t('part.partNo')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="designation"
                            :label="$t('part.description')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="systemName"
                            :label="$t('part.system')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="hostNumber"
                            :label="$t('part.unit')"
                    >
                    </el-table-column>

                    <el-table-column :label="$t('part.qty')" width="180">
                        <template slot-scope="scope">
                            <el-input-number
                                    size="mini"
                                    :min="min"
                                    v-model="scope.row.partsQuantity">
                            </el-input-number>
                        </template>
                    </el-table-column>

                    <el-table-column
                    prop="purchasePriceChn"
                    :label=" $t('part.priceC')"
                    >
                    </el-table-column>
                    <el-table-column
                    prop="purchasePriceIdr"
                    :label=" $t('part.priceI')"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="salesPrice"
                            :label=" $t('part.price')"
                    >
                        <template slot-scope="scope">
                            {{['CNY', "IDR", 'USD'][parseInt(scope.row.currency) - 1]}} {{scope.row.salesPrice}}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('operate')">
                        <template slot-scope="scope">
                            <div class="delete">
                                <i class="el-icon-delete" @click="deleteItem(scope.$index)"> </i>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <span slot="footer">
                <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
                <el-button type="info" @click="submitForm(0)">{{$t('save')}}</el-button>
                <el-button type="primary" @click="submitForm(1)">{{$t('confirm')}}</el-button>
            </span>
        </el-dialog>
        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible"/>
    </div>
</template>

<script>
    import {
        getPoList,
        addPo,
        updatePo,
        uploadPurchaseExcel,
        getPoDetail,
        getStockOutNo,
        deletePurchaseRequest
    } from "../../api/service";
    import crumb from '@/components/common/crumb'
    import pagination from '@/components/common/pagination'
    import mixins from '../../util/mixins';
    import spMixins from '../../util/spMixins'
    import {ERROR_OK} from "../../util/config";
    import PartItem from '@/components/part/sparePartItem'

    export default {
        name: "purchase",
        mixins: [mixins, spMixins],
        data() {
            return {
                dialogVisible: false,
                partVisible: false,
                stockOutList: [],
                methods: {
                    1: "Consignment",
                    2: "Import",
                    3: "Local Purchase"
                },
                po: {
                    id: '',
                    purchaseNumber: '',
                    purchaseMethod: 1,
                    purchaseDateStr: '',
                    purchaseFile: '',
                    stockOutId: '',
                    applyDepartment: '',
                    applicant: ''
                },
                rule: {
                    purchaseNumber: [
                        {required: true, message: 'Purchase Number is none', trigger: 'blur'},
                        {max: 10, message: 'Max length is 10', trigger: 'change'}
                    ],
                    purchaseMethod: [{required: true, message: 'Purchase Method Should not be none', trigger: 'blur'}]
                },
                poList: [],
                partList: []
            }
        },
        computed: {
            list() {
                return this.poList.slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize);
            }
        },
        created() {
            this.getPo();
            this.getStockOut()
        },
        methods: {
            downloadTemplate() {
                window.open('http://cdn.ayotrust.com/upload/2020-01-05/631/采购配件模版.xls');
            },
            async expand(row) {
                if (row.partList) {
                    return
                } else {
                    const {status, data} = await getPoDetail(row.id);
                    if (status === ERROR_OK) {
                        this.$set(row, 'partList', data.iecPurchaseDetailList)
                    }
                }
            },
            deleteOrder(row) {
                const _this = this
                this.$confirm(this.$t('delete'), '', {
                    cancelButtonText: this.$t('cancel'),
                    confirmButtonText: this.$t('confirm')
                }).then(async () => {
                    const {status, msg} = await deletePurchaseRequest(row.id)
                    if (status === ERROR_OK) {
                        _this.$notify.success('Success')
                        _this.getStockOut()
                    } else {
                        _this.$notify.error(msg)
                    }
                }).catch(err => {
                })
            },
            async getStockOut() {
                const {status, data} = await getStockOutNo();
                if (status === ERROR_OK) {
                    this.stockOutList = data
                }
            },
            async edit(row) {
                const {status, data} = await getPoDetail(row.id);
                if (status === ERROR_OK) {
                    this.po = data;
                    this.partList = data.iecPurchaseDetailList;
                    this.dialogVisible = true
                }
            },
            // 重写add方法
            add(list) {
                list.forEach(item => {
                    this.$set(item, 'partsQuantity', 1);
                    this.$set(item, 'originPrice', item.salesPrice);
                });
                if (this.partList.length) {
                    this.partList.forEach(part => {
                        list.forEach((item, idx) => {
                            if (item.partsNumber === part.partsNumber) {
                                part.number = part.number ? part.number + 1 : 1;
                                list.splice(idx, 1);
                            }
                        });
                    });
                    this.partList = this.partList.concat(list);
                } else {
                    this.partList = this.partList.concat(list);
                }
                this.dbVisible = false;
            },
            submitForm(status) {
                this.$refs.form.validate(async valid => {
                    if (valid) {
                        const {
                            id,
                            purchaseNumber,
                            purchaseMethod,
                            purchaseDateStr,
                            purchaseFile,
                            stockOutId,
                            applyDepartment,
                            applicant
                        } = this.po;
                        let purchaseDetails = this.partList.map(item => {
                            return {
                                partsId: item.partsId,
                                partsQuantity: item.partsQuantity,
                                partsPrice: item.purchasePriceChn || item.purchasePriceIdr || item.salesPrice
                            }
                        });
                        purchaseDetails = JSON.stringify(purchaseDetails)
                        if (!id) {
                            const po = {
                                purchaseNumber,
                                purchaseMethod,
                                purchaseDateStr,
                                purchaseFile,
                                stockOutId,
                                applyDepartment,
                                applicant,
                                purchaseDetails,
                                status
                            };
                            const {status} = await addPo(po);
                            if (status === ERROR_OK) {
                                this.getPo();
                                this.clear();
                                this.dialogVisible = false;
                                this.$message.success('Add success')
                            }
                        } else {
                            const po = {
                                id,
                                purchaseNumber,
                                purchaseMethod,
                                purchaseDateStr,
                                purchaseFile,
                                stockOutId,
                                applyDepartment,
                                applicant,
                                purchaseDetails,
                                status
                            };
                            const {status} = await updatePo(po);
                            if (status === ERROR_OK) {
                                this.getPo();
                                this.clear();
                                this.dialogVisible = false;
                                this.$message.success('Update success')
                            }
                        }
                    }
                })
            },
            async fileChange(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('exFiles', item);
                    formData.append('purchaseOrderNumber', this.po.purchaseNumber);
                    formData.append('purchaseMethod', this.po.purchaseMethod);
                    formData.append('purchaseDate', this.po.purchaseDateStr);
                });
                const {status, data} = await uploadPurchaseExcel(formData);
                if (status === ERROR_OK) {
                    this.partList = data.data;
                    this.po.purchaseFile = data.file_path[0]
                }
                e.target.value = ''
            },
            async getPo() {
                const {status, data} = await getPoList();
                if (status === ERROR_OK) {
                    this.poList = data;
                    this.total = data.length
                }
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear()
            },
            clear() {
                this.po = {
                    id: '',
                    purchaseNumber: '',
                    purchaseMethod: 1,
                    purchaseDateStr: '',
                    purchaseFile: '',
                    stockOutId: ''
                };
                this.partList = []
            }
        },
        components: {
            crumb,
            pagination,
            PartItem
        },
    }
</script>

<style scoped lang="scss">
    .label {
        width: 200px;
        line-height: 30px;
        height: 30px;
        border-radius: 5px;
        text-align: center;
        display: inline-block;
        background: #409eff;
        color: #fff;
        cursor: pointer;
    }
</style>